//
//  YYYLoginViewController.swift
//  HotNews
//
//  Created by YYY on 2017/10/10.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit
import SVProgressHUD

class YYYLoginViewController: UIViewController {

    //浏览视图
    private lazy var myWebView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置根视图
        view = myWebView
        
        //设置背景颜色
        view.backgroundColor = UIColor.white
        
        //禁止滚动
        myWebView.scrollView.isScrollEnabled = false
        
        title = "登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 14, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 14, target: self, action: #selector(autoFill), isBack: false)
        //加载授权界面
        loadOAUthPage()
        //设置代理
        myWebView.delegate = self
        // Do any additional setup after loading the view.
    }

    //加载授权界面
    private func loadOAUthPage()
    {
        //确定URL
        let urlString = "\(OAuthUrlString)?client_id=\(SinaAppKey)&redirect_uri=\(SinaAppRedirect_uri)"
        guard let url = URL(string: urlString) else
        {
            return
        }
        
        //建立请求
        let request = URLRequest(url: url)
        
        //加载请求
        myWebView.loadRequest(request)
    }
    
    //关闭
    @objc private func close()
    {
        dismiss(animated: true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    //自动填充
    @objc private func autoFill()
    {
        let js = "document.getElementById('userId').value = '';" + "document.getElementById('passwd').value = ''"
        //加载js代码
        myWebView.stringByEvaluatingJavaScript(from: js)
    }
}

// MARK: UIWebView的代理方法
extension YYYLoginViewController: UIWebViewDelegate
{
    
    /// UIWebView的代理方法
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航栏类型
    /// - Returns: 是否加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.absoluteString.hasPrefix(SinaAppRedirect_uri) == false
        {
            return true
        }
        if request.url?.query?.hasPrefix("code=") == false
        {
            print("取消授权")
            close()
            return false
        }
        let queryString = request.url?.query ?? ""
        
        let length = ("code=" as NSString).length
        let code = (queryString as NSString).substring(from: length)
        print("code = \(code)")

        YYYNetworkManager.shared.loadOAUth(code: code) { (isSuccess) in
            if !isSuccess
            {
                SVProgressHUD.showInfo(withStatus: "网络请求出错")
            }
            else
            {
                //发送登陆成功的通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserLoginSuccessedNotification), object: nil)
                self.close()
            }
        }
        return false
    }
    
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //结束加载
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
